<?php
namespace app\manage\traits;

/**
 * @author:      adv30
 * @DateTime:    2017-07-15
 * @Description: 发送数据
 */
trait SendData {
    /**
     * 把数据发送给指定url,示例如下
     *  $url = 'http://bigmall.local/api_1.html';
     *  $data = array(
     *       "module"=>"user",
     *       "controller"=>"apiuser",
     *       "action"=>"userInfo",
     *       "textData"=>'{"userId":"1"}'
     *   );
     *  $sendObj = new ApiBase();
     *  $data = $sendObj->createData( $data, true );
     *  $res = $sendObj->sendData($url,$data );
     *
     * @param  array    $data       [要发送的数据,数组,键值对]
     * @return bool     $res        [返回发送状态]
     */
    public static function sendData(string $url, $data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_TIMEOUT, 600);
        //curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);        
        //curl_setopt($ch, CURLOPT_REFERER,_REFERER_);        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode( $output, true );
    }

    /*单个发送的*/
    public static function sendDataOne(string $url, $data){
        $res = self :: sendData($url, $data);
        return $res['res'][0];
    }

    /*多个发送的*/
    public static function sendDataLots(string $url, $data){
        $res = self :: sendData($url, $data);
        if($res['failure'] > 0){
            $res['msg'] = $res['res'][$res['failureIndex']]['msg'];
            $res['code'] = $res['res'][$res['failureIndex']]['code'];
        }else{
            $res['msg'] = '操作成功';
            $res['code'] = SUCCESS_CODE;
        }
        $newRes = [];
        foreach ($res['res'] as $k => $v) {
            $newRes[$k] = $v['res']; 
        }
        $res['res'] = $newRes;
        return $res;
    }
}